import React from 'react';
import { Row, Col, Form, Button, Radio, Table, message, Popconfirm } from 'antd';
import { connect } from 'dva';
import CostDetail from '../components/CostDetail';
const R = require('ramda');
import RightBox from '../../../components/commons/RightBox';
import RightConstants from '../../../utils/RightConstants';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
export default connect(({ orderCost, customerManage }) => ({ orderCost, customerManage }))((
    Form.create({ wrappedComponentRef: true })(class Cost extends React.Component {
        constructor(props) {
            super(props);
        }

        handleSearch = (e) => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.orderCost.page;
            newPage.page = 1;
            this.props.dispatch({
                type: 'orderCost/queryOrderCost',
                payload: {
                    orderId: R.isNil(this.props.dataSource) || R.isNil(this.props.dataSource.id) ? "" : this.props.dataSource.id,
                    status: R.isNil(e) ? values.status : e.target.value,
                    page: newPage
                }
            });
        };

        collectCostSearchCondition = () => {
            let conditions = this.props.form.getFieldsValue();
            conditions.id = R.isNil(this.props.dataSource) || R.isNil(this.props.dataSource.id) ? "" : this.props.dataSource.id;
            conditions.orderId = R.isNil(this.props.dataSource) || R.isNil(this.props.dataSource.id) ? "" : this.props.dataSource.id;
            conditions.page = this.props.orderCost.page;
            return conditions;
        }

        handleViewCost = (record) => {
            this.props.dispatch({type: 'customerManage/queryCustomerManageList', payload: {status: 4}});//查询工厂供应商列表
            this.props.dispatch({type: 'logisticsSupplier/getSupplierList'});//查询物流供应商列表
            this.costDetail.handleOpen(record, "1", R.isNil(this.props.dataSource) ? {} : this.props.dataSource, {});
        }

        handleAddCost = () => {
            this.props.dispatch({type: 'logisticsSupplier/getSupplierList'});
            this.costDetail.handleOpen({}, "2", R.isNil(this.props.dataSource) ? {} : this.props.dataSource, this.collectCostSearchCondition());
        }

        handleApprovalCost = (record) => {
            this.props.dispatch({type: 'customerManage/queryCustomerManageList', payload: {status: 4}});//查询工厂供应商列表
            this.props.dispatch({type: 'logisticsSupplier/getSupplierList'});//查询物流供应商列表

            this.costDetail.handleOpen(record, "3", R.isNil(this.props.dataSource) ? {} : this.props.dataSource, this.collectCostSearchCondition());
        }

        handleDeleteCost = (record) => {
            this.props.dispatch({
                type: 'orderCost/deleteOrderCost',
                payload: {
                    id: record.id,
                    searchConditions: this.collectCostSearchCondition()
                }
            });
        }

        handleConfirmCost = () => {
            let status = this.props.type === "1" ? "3" : "2";
            let searchConditions = this.props.searchConditions;
            this.props.dispatch({
                type: 'orderCost/confirmCost',
                payload: {
                    id: R.isNil(this.props.dataSource) || R.isNil(this.props.dataSource.id) ? "" : this.props.dataSource.id,
                    status: status,
                    onSuccess: () => {
                        this.props.dispatch({
                            type: 'orderManage/queryOrderManageList',
                            payload: searchConditions
                        })
                    }
                }
            });
            this.props.form.resetFields();
            if (this.props.handleCancel) {
                this.props.handleCancel();
            }
        }

        handleResetFields = () => {
            this.props.form.resetFields();
        }

        columns = [
            {
                title: '订单编号', dataIndex: 'orderno', key: 'orderno',
                render: (text, record, index) => {
                    return <span>{R.isNil(this.props.dataSource) || R.isNil(this.props.dataSource.orderno) ? "" : this.props.dataSource.orderno}</span>;
                }
            },
            {
                title: '订单协议号', dataIndex: 'contractno', key: 'contractno',
                render: (text, record, index) => {
                    return <span>{this.props.dataSource && this.props.dataSource.contractno ? this.props.dataSource.contractno : ""}</span>;
                }
            },
            { title: '费用种类', dataIndex: 'chargeTypeName', key: 'chargeTypeName' },
            { title: '币种', dataIndex: 'chargeCurrency', key: 'chargeCurrency' },
            { title: '汇率', dataIndex: 'rate', key: 'rate' },
            { title: '金额', dataIndex: 'cost', key: 'cost' },
            { title: '余额', dataIndex: 'balance', key: 'balance' },
            { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
            {
                title: '状态', dataIndex: 'status', key: 'status',
                render: (text, record, index) => {
                    return record.status === "3" ? "已确认" : "草稿";
                }
            },
            {
                title: '操作', key: 'key_oprator',
                render: (text, record, index) => {
                    let split = <span className="ant-divider" />
                    let viewLink = <a href="#" onClick={this.handleViewCost.bind(this, record)} >查看</a>
                    let rightKey = this.props.type === "1" ? "ORDER_MANAGE_COST_APPROVAL" : "ORDER_APPROVAL_COST_APPROVAL";
                    let approvalLink = <RightBox resource={rightKey}><a href="#" onClick={this.handleApprovalCost.bind(this, record)}>编辑</a></RightBox>
                    let deleteLink = <Popconfirm onConfirm={this.handleDeleteCost.bind(this, record)} okText="是" cancelText="否" placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除？'}>
                        <a href="#">删除</a>
                    </Popconfirm>
                    let operaters = {
                        "2": this.props.disabled ? <span>{viewLink}</span> : <span>{this.props.type === "1" ? approvalLink : viewLink}{split}{this.props.type === "1" ? deleteLink : ""}</span>,
                        "3": <span>{viewLink}</span>,
                    }
                    return (operaters[record.status])
                }
            }];

        render() {
            const { getFieldDecorator } = this.props.form;
            let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;
            let formItemLayout = {
                labelCol: { xs: { span: 24 }, sm: { span: 6 } },
                wrapperCol: { xs: { span: 24 }, sm: { span: 14 } }
            };
            let values = this.props.form.getFieldsValue();
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                current: this.props.orderCost.page.page,
                pageSize: this.props.orderCost.page.size,
                total: this.props.orderCost.page.totalRow,
                showSizeChanger: true,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.orderCost.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'orderCost/queryOrderCost',
                        payload: {
                            id: R.isNil(dataSource.id) ? "" : dataSource.id,
                            status: values.status,
                            page: newPage
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = this.props.orderCost.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'orderCost/queryOrderCost',
                        payload: {
                            id: R.isNil(dataSource.id) ? "" : dataSource.id,
                            status: values.status,
                            page: newPage
                        }
                    });
                }
            }

            let showConfirmButoon = false;
            let rightKey = this.props.type === "1" ? "ORDER_MANAGE_COST_CONFIRM" : "ORDER_APPROVAL_COST_CONFIRM";
            if (dataSource.status === "6") {//报关中
                if (this.props.type === "1" && dataSource.chargestatus === "1") showConfirmButoon = true;//订单尚未确认申报完毕 且通关已确认
                else if (this.props.type === "2" && dataSource.chargestatus === "0") showConfirmButoon = true;//通关尚未确认申报完毕
            }

            let showAddButton = false;
            if ((this.props.type === "1" && dataSource.chargestatus !== "2")) {
                showAddButton = true;
            }

            return (
                <div>
                    <Form>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label={'状态'}>
                                    {getFieldDecorator('status', {
                                        initialValue: "2"
                                    })(
                                        <RadioGroup style={{ width: 800 }} onChange={value => this.handleSearch(value)}>
                                            <Radio value="2">草稿</Radio>
                                            <Radio value="3">已确认</Radio>
                                        </RadioGroup>
                                        )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem>
                                    <Button type="primary" icon="plus" size={'default'} disabled={this.props.disabled} onClick={this.handleAddCost.bind(this)} style={{ display: showAddButton ? 'inline-block' : 'none' }}>添加费用</Button>
                                    <RightBox resource={RightConstants.ORDER[rightKey]}>
                                        <Popconfirm onConfirm={this.handleConfirmCost.bind(this)} okText="是" cancelText="否"
                                            placement="leftTop" title={'请注意！确认费用申报完毕是退税的必要步骤，确认之后将不能再次添加费用，请确认是否申报完毕?'}>
                                            <Button type="primary" icon="check" style={{ marginLeft: 50, display: showConfirmButoon ? 'inline-block' : 'none' }} size={'default'} disabled={this.props.disabled}>确认申报完毕</Button>
                                        </Popconfirm>
                                    </RightBox>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    <Table rowKey={record => record.id} dataSource={this.props.orderCost.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination} scroll={{ x:true }} />
                    <CostDetail wrappedComponentRef={(inst) => this.costDetail = inst} dispatch={this.props.dispatch} type={this.props.type} customs={this.props.customs} />
                </div>
            )
        }
    })
))